package com.yswee.mallnavi.activity.base;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Toast;

import com.yswee.framework.R;
import com.yswee.framework.activity.IActivityContext;
import com.yswee.framework.manager.ActivityManager;
import com.yswee.framework.net.ITask;
import com.yswee.framework.net.ITaskContext;
import com.yswee.framework.utils.OSUtils;
import com.yswee.framework.utils.ViewInjectUtils;
import com.yswee.framework.utils.statusbar.StatusBarCompat;
import com.yswee.framework.widget.MToast;
import com.yswee.mallnavi.activity.MainActivity;
import com.yswee.mallnavi.activity.common.ScreenSaverActivity;
import com.yswee.mallnavi.entity.Account;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public abstract class BaseActivity extends Activity implements ITaskContext, IActivityContext {

	protected boolean mIsPaused;
	private Handler mHandlerScreenSaver = new Handler();
	private Runnable mRunningGotoScreenSaver = new Runnable() {
		@Override
		public void run() {
			if (mIsPaused) {
				return;
			}
			startScreenSaver();
		}
	};

	protected ArrayList<WeakReference<ITask>> mRegistTasks = 
			new ArrayList<WeakReference<ITask>>();
	
	@Override
	public void registTask(ITask task) {
		this.mRegistTasks.add(new WeakReference<ITask>(task));
	}
	
	@Override
	public void unregistTask(ITask task) {
		for(int i = 0; i < this.mRegistTasks.size(); i ++) {
			WeakReference<ITask> wf = this.mRegistTasks.get(i);
			if(wf != null && wf.get() != null && wf.get().equals(task)) {
				this.mRegistTasks.remove(i);
				break;
			}
		}
	}
	
	void cancelTasks() {
		for(int i = 0; i < this.mRegistTasks.size(); i ++) {
			WeakReference<ITask> wf = this.mRegistTasks.get(i);
			if(wf != null && wf.get() != null) {
				wf.get().cancel();
			}
		}
	}
	/**
	 * 是否开启硬件加速
	 * @return
	 */
	protected boolean enabledHardwareAccelerated() {
		return true;
	}

	/**
	 * 开启硬件加速
	 */
	@SuppressLint("InlinedApi")
	protected void onHardwareAccelerated() {
		if(enabledHardwareAccelerated()) {
			if (OSUtils.hasHoneycomb()) {
				getWindow().setFlags(
					WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED, 
					WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
			}
		}
	}

	/**
	 * 取得传递的参数
	 */
	protected void onQueryArguments(Intent intent) {
		
	}
	
	/**
	 * 初始化控件、获取内部控件（注释类遍历）
	 */
	protected void onInjectView() {
		ViewInjectUtils.onInjectView(this);
	}
	
	/**
	 * 初始化控件、获取内部控件
	 */
	protected void onFindView() {
		
	}
	
	/**
	 * 设置监听事件
	 */
	protected void onBindListener() {
		
	}
	
	/**
	 * 加载数据
	 */
	protected void onApplyData() {
		
	}
	
	@Override
	public void setContentView(int layoutResID) {
		super.setContentView(layoutResID);
		initContentView();
	}
	
	@Override
	public void setContentView(View view) {
		super.setContentView(view);
		initContentView();
	}
	
	@Override
	public void setContentView(View view, LayoutParams params) {
		super.setContentView(view, params);
		initContentView();
	}
	
	/**
	 * 是否全屏
	 * @return
	 */
	protected boolean isFullScreen() {
		return true;
	}

	/**
	 * 是否浮动对话框(转场动画)
	 * @return
	 */
	protected boolean isDialogTheme() {
		return false;
	}
	
	/**
	 * 浅色状态栏
	 * @return
	 */
	protected boolean lightmodeStatusBar() {
		return false;
	}

	/**
	 * 是否屏保
	 * @return
	 */
	protected boolean checkScreenSaver() {
		return true;
	}
	
	/**
	 * 状态栏颜色
	 * @return
	 */
	@SuppressWarnings("deprecation")
	protected int getStatusBarColor() {
		return getResources().getColor(R.color.widget_titlebar_bg);
	}
	
	private void initContentView() {
		onHardwareAccelerated();
		onQueryArguments(getIntent());
		onInjectView();
		onFindView();
		onBindListener();
		onApplyData();
		StatusBarCompat.translucentStatusBar(this, 
				getStatusBarColor(), !isFullScreen());
		StatusBarCompat.setStatusTextColor(this, lightmodeStatusBar());
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && OSUtils.isTranslucentOrFloating(this)) {
            OSUtils.fixOrientation(this);
        }
		super.onCreate(savedInstanceState);
		ActivityManager.get().pushActivity(this);
	}

	@SuppressWarnings("deprecation")
	@Override  
	public Resources getResources() {  
	    Resources res = super.getResources();  
	    Configuration config = res.getConfiguration();
	    if (config.fontScale != 1.0f) {
	    	config.fontScale = 1.0f;
		    res.updateConfiguration(config, res.getDisplayMetrics());  
	    }
	    return res;  
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		mIsPaused = false;
		resetRunningGotoScreenSaver();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		mIsPaused = true;
		mHandlerScreenSaver.removeCallbacks(mRunningGotoScreenSaver);
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		cancelTasks();
		ActivityManager.get().popupActivity(this);
	}
	
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    }
    
	@Override
	public void finish() {
		super.finish();
		if (isDialogTheme()) {
			overridePendingTransition(R.anim.anim_none, 
				R.anim.activity_bottom_out);
		}
	}
	
	@Override
	public void setRequestedOrientation(int requestedOrientation) {
		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && OSUtils.isTranslucentOrFloating(this)) {
            return;
        }
		super.setRequestedOrientation(requestedOrientation);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		resetRunningGotoScreenSaver();
		return super.dispatchTouchEvent(ev);
	}

	@TargetApi(Build.VERSION_CODES.M)
	protected void checkOverlayPermission() {
		if (!Settings.canDrawOverlays(this)) {
			Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
			intent.setData(Uri.parse("package:" + getPackageName()));
			startActivity(intent);
		}
	}

	protected void resetRunningGotoScreenSaver() {
		mHandlerScreenSaver.removeCallbacks(mRunningGotoScreenSaver);
		if (mIsPaused) {
			return;
		}
		if (checkScreenSaver()) {
			mHandlerScreenSaver.postDelayed(mRunningGotoScreenSaver, Account.get().adsDelayInSecond * 1000);
		}
	}

	protected void startScreenSaver() {
		ActivityManager.get().popupAllActivityAfterThis(MainActivity.class);
		startActivity(ScreenSaverActivity.class);
	}

    protected void showToastMessage(String text) {
    	showToastMessage(text, Toast.LENGTH_SHORT);
	}
    
    protected void showToastMessage(String text, int duration) {
    	MToast.showToastMessage(text, duration);
	}
    
    protected void showToastMessage(int resId) {
    	showToastMessage(resId, Toast.LENGTH_SHORT);
	}
    
    protected void showToastMessage(int resId, int duration) {
    	MToast.showToastMessage(resId, duration);
	}
    
    protected void startActivity(Class<?> cls) {
    	startActivity(new Intent(this, cls));
    }
    
    protected void startActivity(String action) {
    	startActivity(new Intent(action));
    }
    
    protected void startActivity(Class<?> cls, Intent data) {
    	if(data == null) {
    		return;
    	}
    	data.setClass(this, cls);
    	startActivity(data);
    }
    
    protected void startActivity(String action, Intent data) {
    	if(data == null) {
    		return;
    	}
    	data.setAction(action);
    	startActivity(data);
    }
    
    protected void startActivityForResult(Class<?> cls, int requestCode) {
    	startActivityForResult(new Intent(this, cls), requestCode);
    }
    
    protected void startActivityForResult(String action, int requestCode) {
    	startActivityForResult(new Intent(action), requestCode);
    }
    
    protected void startActivityForResult(Class<?> cls, Intent data, int requestCode) {
    	if(data == null) {
    		return;
    	}
    	data.setClass(this, cls);
    	startActivityForResult(data, requestCode);
    }
    
    protected void startActivityForResult(String action, Intent data, int requestCode) {
    	if(data == null) {
    		return;
    	}
    	data.setAction(action);
    	startActivityForResult(data, requestCode);
    }
    
    protected void performBackKeyClicked() {
    	new Thread() {
			public void run() {
				try {
					Instrumentation inst = new Instrumentation();
					inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
    }
    
}